<html>
<!-- Copyright 2010  Jacob Brunson  (email : wp-jacob.gpl.license@jacobbrunson.com )

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-->
<head> 
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <script type="text/javascript" src="lib/air/AIRAliases.js"></script>
    <script src="lib/prototype/prototype.js" type="text/javascript"></script>
    <script type="text/javascript" src="lib/gdata/auth.js"></script> 
    <script type="text/javascript" src="lib/gdata/docs.js"></script> 
    <script type="text/javascript" src="lib/AIRUpdater.js"></script>
    <script type="text/javascript">
    
    var filesToUpload = new Array();
    var auth_obj = new GoogleAuth();
    var lastUploadedDiv;
    var currentDiv;
    var divIdNum = 0;
    var uploading = false;
    
    function startapp()
    {
        lastUploadedDiv = $('uploadedfiles');
        auth_obj.retrieveCredentials();
        findFiles();
        if (auth_obj.email == "") {
            $('clearloginbutton').value="Logged Out";
        }
        AIRUpdater.init();
    }
    
    function addArgvFiles(invoke_event)
    {
        for (i = 0; i < invoke_event.arguments.length; i++) {
            air.trace("File added from command line", invoke_event.arguments[i]);
            new_file = new air.File(invoke_event.arguments[i]);
            if (new_file.exists) {
                filesToUpload.push(new_file);
            }
        }
        findFiles();
    }
    
    function findFiles()
    {
        if (filesToUpload.length > 0) {
            logIn();
        }
    }

    function askUserForFiles()
    {
        file_obj = new air.File();
        file_obj.addEventListener(air.FileListEvent.SELECT_MULTIPLE, filesFound);
        i = 0;
        file_types_str = "";
        for (property in G_DOCS_FILE_EXTENSIONS) {
            if (i > 0) {
                file_types_str += ";";
            }
            i++;
            file_types_str += "*" + property;
        }
        file_filter = new air.FileFilter("Documents", file_types_str);
        file_obj.browseForOpenMultiple("Select Files For Uploading", [file_filter]);
    }
    
    function filesFound(file_list_event)
    {
        air.trace("found some files:", file_list_event);
        while (file_list_event.files.length > 0) {
            thisfile = file_list_event.files.pop();
            air.trace("Adding file to upload list", thisfile.name);
            filesToUpload.push(thisfile);
        }
        air.trace("Found "+filesToUpload.length+" files to upload");
        logIn();
    }
    
    function logIn()
    {
        if (uploading) {
            return;
        }
        uploading = true;
        air.trace("Attemping login proceedure", auth_obj);
        auth_obj.connect(loggedIn);
        $('clearloginbutton').value="Clear Login";
    }
    
    function loggedIn(had_success)
    {
        if (had_success) {
            air.trace("Logged in, attempting to upload");
            uploadAFile();
        } else {
            auth_obj.login(loggedIn);
        }
    }
    
    function uploadAFile()
    {
        if (filesToUpload.length > 0) {
            
            numups = air.EncryptedLocalStore.getItem('numberofuploads');
            if (numups == null) {
                numups = new air.ByteArray();
                numups.writeInt(1);
                
            } else {
                num = numups.readInt();
                num++;
                numups = new air.ByteArray();
                numups.writeInt(num);
                if (num == 100) {
                    donate();
                }
            }
            air.EncryptedLocalStore.setItem('numberofuploads', numups);
            
            divIdNum++;
            air.trace("inserting after ", lastUploadedDiv);
            thisfile = filesToUpload.pop();
            newdiv = '<div class="uploadentry"><div id="file-'+divIdNum+'" class="progbar">'+thisfile.name+'</div>';
            newdiv += '<span class="resultmsg" id="resultmsg-'+divIdNum+'"></span></div>';
            air.trace(newdiv);
            Element.insert(lastUploadedDiv, 
                           {after: newdiv});
            currentDiv = $('file-'+divIdNum);
            uploader = new GdataFileUploader(thisfile, auth_obj, progressUploading, fileUploaded, uploadFailed);
            uploader.upload();
        } else {
            uploading = false;
        }
    }
    
    function progressUploading(percent)
    {
        air.trace("Progress", Math.round(percent*100));
        currentDiv.style.width = ""+Math.round(percent*320)+"px";
        currentDiv.style.backgroundColor = "rgb(50,"+Math.round((percent*50)+80)+",50)";
        if (percent >= 1 && $('resultmsg-'+divIdNum).innerHTML == '') {
            air.trace("Waiting for server response");
            $('resultmsg-'+divIdNum).innerHTML = "Waiting for server response...";
        }
    }

    function fileUploaded(docurl)
    {
    air.trace("Done uploading file", docurl);
        if (docurl != null) {
            $('resultmsg-'+divIdNum).innerHTML = "<a class='viewdoc' id='link-"+divIdNum+"' href='"+docurl+"'>View in Web Browser</a>";
            $('link-'+divIdNum).onclick = function(){
                                                h = this.href;
                                                openInBrowser(h);
                                                return false;
                                          };
            uploadAFile();
        } else {
            $('resultmsg-'+divIdNum).innerHTML = "There was an uploading error.";
        }
    }

    function uploadFailed(errormsg)
    {
        currentDiv.style.width = "320px";
        currentDiv.style.backgroundColor = "rgb(110,50,50)";
        $('resultmsg-'+divIdNum).innerHTML = errormsg;
        uploadAFile();
    }
    
    function clearCredentials()
    {
        if ($('clearloginbutton').value != "Logged Out") {
            auth_obj.clear();
            $('clearloginbutton').value="Cleared";
        }
    }
    
    function fileDrop(event)
    {
        air.trace("fileDrop event",  event.dataTransfer.getData("application/x-vnd.adobe.air.file-list"));
        fileList = event.dataTransfer.getData("application/x-vnd.adobe.air.file-list");
        if (fileList == null) {
            air.trace("Null type file dropped");
            return false;
        }
        while (fileList.length > 0) {
            thisfile = fileList.pop();
            air.trace("Adding file to upload list", thisfile.name);
            filesToUpload.push(thisfile);
        }
        air.trace("Found "+filesToUpload.length+" files to upload");
        logIn();
    }
    
    
    function openInBrowser(url)
    {
        air.navigateToURL(new air.URLRequest(url));
        return false;
    }

    function donate()
    {
        openInBrowser('http://uploader.jacobbrunson.com/');
    }
    
    air.NativeApplication.nativeApplication.addEventListener(air.InvokeEvent.INVOKE, addArgvFiles);
    </script>

</head> 
<body onload="startapp();" ondrop="fileDrop(event);" ondragover="event.preventDefault();">
    <form id="toolbar">
    <input type="button" onclick="askUserForFiles();return false;" value="Select Files"/>
    <input type="button" onclick="clearCredentials();return false;" value="Clear Login" id="clearloginbutton"/>
    <input type="button" onclick="donate();return false;" value="Donate"/>
    </form>
    <div align="right" style="display:none;" id="updateavailable">Update Available</div>
    <div id="uploadedfiles"></div>
    <div id="dragnote">Drag Files Here To Upload</div>
</body> 
</html>